<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\UserRequest;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Requests\Api\AuthorizationRequest;
use App\Http\Requests\Api\WeappUserRequest;
use App\Http\Requests\Api\WeappUserRegisterRequest;
use Illuminate\Support\Str;
use Auth;
use App\Transformers\UserTransformer;

class AuthorizationsController extends Controller
{
    public function weappLogin(WeappUserRequest $request)
    {
        $code = $request->code;
        // 通过 code 拿到微信 openid 和 session_key
        $miniProgram = \EasyWeChat::miniProgram();
        $data = $miniProgram->auth->session($code);

        if (isset($data['errcode'])) {
            return $this->responese->errorUnauthorized('code 不正确');
        }

        // 查询用户是否存在
        $user = User::where(['weapp_openid' => $data['openid']])->CollectCount()->followersCount()->followingsCount()->moviesCount()->first();
        if (! $user) {
            // 注册一个昵称 头像 为空的新用户
            $user = $this->registerUser($data['openid']);
        }

        $attributes['weixin_session_key'] = $data['session_key'];
        $user->update($attributes);
        $token = Auth::guard('api')->fromUser($user);
        return $this->response->item($user, new UserTransformer())
            ->setMeta([
                'access_token' => \Auth::guard('api')->fromUser($user),
                'token_type' => 'Bearer',
                'expires_in' => \Auth::guard('api')->factory()->getTTL() * 60
            ])
            ->setStatusCode(201);
    }

    public function weappRegister(WeappUserRegisterRequest $request)
    {
        $code = $request->code;
        $miniProgram = \EasyWeChat::miniProgram();
        $data = $miniProgram->auth->session($code);

        if (isset($data['errcode'])) {
            return $this->responese->errorUnauthorized('code 不正确');
        }

        $user = User::where(['weapp_openid' => $data['openid']])->CollectCount()->first();
        if (!$user) {
            $user = $this->registerUser($data['openid'], $data['session_key'], $request->name, $request->avatar);
        } else {
            $user->update([
                'name' => $request->name,
                'avatar' => $request->avatar,
            ]);
        }
        $token = Auth::guard('api')->fromUser($user);
        return $this->response->item($user, new UserTransformer())
            ->setMeta([
                'access_token' => \Auth::guard('api')->fromUser($user),
                'token_type' => 'Bearer',
                'expires_in' => \Auth::guard('api')->factory()->getTTL() * 60
            ])
            ->setStatusCode(201);
    }

    public function login(Request $request)
    {
        $username = $request->input('name');
        filter_var($username, FILTER_VALIDATE_EMAIL) ?
            $where['email'] = $credentials['email'] = $username :
            $where['name'] = $credentials['name'] = $username;
        $credentials['password'] = $request->password;
        if (!$token = \Auth::guard('api')->attempt($credentials)) {
            return $this->response->errorUnauthorized('用户名或密码错误');
        }
        $user = User::where($where)->CollectCount()->first();
        return $this->response->item($user, new UserTransformer())
            ->setMeta([
                'access_token' => \Auth::guard('api')->fromUser($user),
                'token_type' => 'Bearer',
                'expires_in' => \Auth::guard('api')->factory()->getTTL() * 60
            ])
            ->setStatusCode(201);
    }

    public function weappUpdateUserInfo()
    {

    }

    public function update()
    {
        $token = Auth::guard('api')->refresh();
        return $this->respondWithToken($token);
    }

    public function destroy()
    {
        Auth::guard('api')->logout();
        return $this->response->noContent();
    }

    protected function respondWithToken($token)
    {
        return $this->response->array([
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => \Auth::guard('api')->factory()->getTTL() * 60
        ]);
    }
    /**
     * 注册新用户
     *
     * @param string $openid
     * @param string $name
     * @param string $session_key
     * @param string $avatar
     * @return App\Models\User
     */
    protected function registerUser($openid, $session_key = '', $name = '', $avatar = '')
    {
        $user = User::create([
            'weapp_openid' => $openid,
            'avatar' => $avatar,
            'name' => $name,
            'password' => bcrypt(Str::random(32)),
            'weixin_session_key' => $session_key,
        ]);
        $user->setting()->create(['user_id' => $user->id]);
        // 管理员自动关注
        User::find(1)->follow($user->id);
        $user->follow(1);
        return $user;
    }

    public function register(UserRequest $request)
    {
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password),
        ]);
        $user->setting()->create(['user_id' => $user->id]);
        User::find(1)->follow($user->id);
        $user->follow(1);
        return $this->response->created();
    }
}
